/*******************************************************************************
 * Copyright (c) 2014 Francesco Gabbrielli.
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Francesco Gabbrielli - initial API and implementation
 ******************************************************************************/
package it.francescogabbrielli.android.solidalapp.profile;

import it.francescogabbrielli.android.solidalapp.BaseFragment;
import it.francescogabbrielli.android.solidalapp.DataEvent;
import it.francescogabbrielli.android.solidalapp.IntentAction;
import it.francescogabbrielli.android.solidalapp.SolidalApp;
import it.francescogabbrielli.android.solidalapp.NetworkUtils.Status;
import it.francescogabbrielli.android.solidalapp.R;
import it.francescogabbrielli.android.solidalapp.StatusEvent;
import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;
import it.francescogabbrielli.android.solidalapp.deviceendpoint.model.Device;
import it.francescogabbrielli.android.solidalapp.profileendpoint.model.Profile;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 
 */
public class ProfileFragment extends BaseFragment<ProfileFragmentListener> implements TextWatcher {

	public ProfileFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		return inflater.inflate(R.layout.fragment_profile, container, false);
	}

	private boolean modified;
		
	@Override
	public void onStop() {
		
		// Save on exit
		View view = getView();
		if(modified && view!=null) {
			
			Profile profile = (Profile) app.getData(DataKey.PROFILE);
			Device device = (Device) app.getData(DataKey.DEVICE);
			
			EditText t = (EditText) view.findViewById(R.id.profile_name_edit);
			profile.setUsername(t.getText().toString());
			
			t = (EditText) view.findViewById(R.id.profile_phone_edit);
			profile.setDefaultPhone(t.getText().toString());
			device.setTelephoneNumber(t.getText().toString());
			
			IntentAction.ENDPOINTS_UPDATE_PROFILE.start(getActivity());
			modified = false;
		}

		super.onStop();
	}
	
	@Override
	public void afterTextChanged(Editable s) {
		modified = true;
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		
	}
	
	@Override
	public void onStatusUpdate(StatusEvent event) {
		updateStatus();
	}
	
	@Override
	public void onDataChanged(DataEvent event) {
		
		updateStatus();
		
		switch (event.getKey()) {
		case DEVICE:
		case PROFILE:
			updateProfile();
			break;

		default:
			break;
		}
	}
	
	private void enable(boolean enabled) {
		View view = getView();
		if(view!=null) {
			((EditText) view.findViewById(R.id.profile_name_edit)).setEnabled(enabled);
			((EditText) view.findViewById(R.id.profile_phone_edit)).setEnabled(enabled);
		}
	}

	private void updateStatus() {
		View view = getView();
		if (view!=null) {
			String status = "Non connesso";
			if (app.getStatus().getNetworkStatus()==Status.CONNECTED) {
				status = "Non registrato";
				if (app.getStatus().getGcmId()!=null) {
					status = "In fase di registrazione";
					if (app.getData(DataKey.DEVICE)!=null)
						status = "Registrato";
				}
			}
			status += " - Profilo ";
			status += app.getData(DataKey.PROFILE)!=null ? "OK" : "KO";
	
			TextView tv = (TextView) view.findViewById(R.id.profile_status_text);
			tv.setText(status);
		}
	}
	
	private void updateProfile() {
		
		Profile profile = (Profile) app.getData(DataKey.PROFILE);
		Device device = (Device) app.getData(DataKey.DEVICE);
		
		enable(profile!=null && device!=null);
		
		View view = getView();
		if (profile==null || view==null)
			return;
		
		String nr = null;
		if (device!=null)
			nr = device.getTelephoneNumber();
		if(nr==null || "".equals(nr))
			nr = profile.getDefaultPhone();
		if (nr==null || "".equals(nr)) {
			TelephonyManager tel = (TelephonyManager) app.getSystemService(Context.TELEPHONY_SERVICE);
			nr = tel.getLine1Number();
			modified = nr!=null && !"".equals(nr);
			Log.i(SolidalApp.TAG, "LOAD DEFAULT PHONE: "+nr);
		}

		EditText t = (EditText) view.findViewById(R.id.profile_account_edit);
		t.setText(profile.getGoogleId());
		
		t = (EditText) view.findViewById(R.id.profile_name_edit);
		t.removeTextChangedListener(this);
		t.setText(profile.getUsername());
		t.addTextChangedListener(this);
				
		t = (EditText) view.findViewById(R.id.profile_phone_edit);
		t.removeTextChangedListener(this);
		t.setText(nr);
		t.addTextChangedListener(this);
		
		t = (EditText) view.findViewById(R.id.profile_credits_edit);
		t.setText(profile.getCredits()!=null ? profile.getCredits().toString() : "");
	
	}

}
